#include "ftpserver.h"
#include <signal.h>
#include <sys/stat.h>
#include <pthread.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("use %s ip port\n", argv[0]);
        exit(-1);
    }
    signal(SIGCHLD, my_sighandler);
    int sockfd = init_tcpserver(argv[1], atoi(argv[2]));
    if (-1 == sockfd) {    /*创建失败退出*/
        exit(-1);
    }
    /*在服务器的当前目录创建日志文件夹*/
    char curr_dir[256] = {0};
    getcwd(curr_dir, sizeof(curr_dir));
    mkdir("./log", 0777);
    /*更换目录到共享文件夹下*/
    chdir(FTPDIR);
    while (1) {
        int *confd = (int *)malloc(sizeof(int));
        struct sockaddr_in caddr;
        memset(&caddr, 0, sizeof(caddr));
        socklen_t len = sizeof(caddr);
        *confd = accept(sockfd, (struct sockaddr *)&caddr, &len);
        pid_t pid = fork();
        if (pid == 0) {
            close(sockfd);
            CLI_INFO *pcli = (CLI_INFO *)malloc(sizeof(CLI_INFO));
            memset(pcli, 0, sizeof(CLI_INFO));
            strcpy(pcli->ip, inet_ntoa(caddr.sin_addr));
            pcli->port = ntohs(caddr.sin_port);
            pcli->fd = *confd;
            char filename[256] = {0};
            sprintf(filename, "%s/log/%s_%d.txt", curr_dir, pcli->ip, pcli->port);
            pcli->fp = fopen(filename, "w+");
            if (pcli->fp == NULL) {
                perror("fopen failed");
            }
            CLI_MES *mes = (CLI_MES *)malloc(sizeof(CLI_MES));
            mes->pcli = pcli;
            mes->cmd_no = 100;
            pthread_t tid;
            pthread_create(&tid, NULL, log_handle, (void *)mes);
            handle_connection(pcli);
            exit(0);
        } else if (pid > 0) {
            close(*confd);
        } else {
            perror("fork error!");
            printf("handle connection failed:%s:%d\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
        }
    }
    close(sockfd);
    return 0;
}

